<?php

class Request_Http extends Request
{
	
	/**
	 * @var string
	 */
	protected $_uri = null;
	
	/**
	 * @var array
	 */
	protected static $_alias = null;
		
	/**
	 * constructor.
	 */
    public function __construct()
    {
        $path =  $this->getPath();
        
        $path = strtolower(trim($path, '/'));
		
		if(null === self::$_alias)
		{
			self::$_alias =  Agilet::loadConfig('alias');
		}

		if(isset(self::$_alias[$path]))
		{
			$path = self::$_alias[$path];
		}
		
		$path = str_replace('-', '', $path);
				
		if(empty($path)){
			$path = 'index';
		}
		
		$arr = explode('/', $path);
		
		$this->_method = strtoupper($_SERVER['REQUEST_METHOD']);
		
		$module =  null;
		
		if(isset($arr[0]))
		{
			if ($arr[0] == 'admin')
	        {
	            $this->_amode = 'admin';
	            if (isset($arr[1]) && Agilet::hasModule($arr[1]))
	            {
	                $module = $arr[1];
	                unset($arr[1]);
	            }else{
	            	$module = 'core';
	            }
	        }
	        else if(Agilet::hasModule($arr[0])){
	            $module = $arr[0];
	            unset($arr[0]);
	        }else{
	        	$module =  'core';
	        }
	        	
		}
		
		if(null == $arr)
		{
			$arr =  array('index');
		}

        $this->_class = $this->_findClass($module, $arr);
        
        if(null == $this->_class)
        {
           require_once SYSTEM_MODULE_PATH. '/core/class/action/error/404.php';
           $this->_class = 'Core_Action_Error_404';
        }
		
    }
	

    protected function _findClass($module, &$arr)
    {
        
       do{
       	
			$sub = implode('_', array_map('ucfirst', $arr));
	
    	    $file = $module . '/class/action/' . str_replace('_', '/', strtolower($sub));
			
            if (file_exists($filename = SYSTEM_MODULE_PATH . '/' . $file . '.php'))
            {
                require_once $filename;
                return inflect($module) . '_Action_' . $sub;
            }
            else
            if (file_exists($filename = SYSTEM_MODULE_PATH . '/' . $file . '/index.php'))
            {
                require_once $filename;
                return inflect($module) . '_Action_' . $sub . '_Index';
            }
            
            // remove last eelement of $arr
            
            $len = count($arr);
            
			// remove position 
            if($len){
                $arr=  array_slice($arr, 0, $len-1);
            }
            
        }while($len > 1);
        
        return null;
    }
    /**
     * @return string
     */
    public function getUri()
    {
        if(null === $this->_uri){
            $uri = null;
            if (isset($_SERVER['HTTP_X_REWRITE_URL'])) { // check this first so IIS will catch
                $uri = $_SERVER['HTTP_X_REWRITE_URL'];
            } elseif (
                // IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem)
                isset($_SERVER['IIS_WasUrlRewritten'])
                && $_SERVER['IIS_WasUrlRewritten'] == '1'
                && isset($_SERVER['UNENCODED_URL'])
                && $_SERVER['UNENCODED_URL'] != ''
                ) {
                $uri = $_SERVER['UNENCODED_URL'];
            } elseif (isset($_SERVER['REQUEST_URI'])) {
                $uri = $_SERVER['REQUEST_URI'];
                // Http proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path
                $schemeAndHttpHost = self::getScheme() . '://' . $this->getHttpHost();
                if (strpos($uri, $schemeAndHttpHost) === 0) {
                    $uri = substr($uri, strlen($schemeAndHttpHost));
                }
            } elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0, PHP as CGI
                $uri = $_SERVER['ORIG_PATH_INFO'];
                if (!empty($_SERVER['QUERY_STRING'])) {
                    $uri .= '?' . $_SERVER['QUERY_STRING'];
                }
            }
            $this->_uri  = $uri;
        }
        return $this -> _uri;
    }
/**
     * Retrieve an array of parameters
     *
     * Retrieves a merged array of parameters, with precedence of userland
     * params (see {@link setParam()}), $_GET, $_POST (i.e., values in the
     * userland params will take precedence over all others).
     *
     * @return array
     */
    public function getParams()
    {
        return $this -> _params + $_GET + $_POST;
    }

    /**
     * Retrieve a parameter
     *
     * Retrieves a parameter from the instance. Priority is in the order of
     * userland parameters (see {@link setParam()}), $_GET, $_POST. If a
     * parameter matching the $key is not found, null is returned.
     *
     * If the $key is an alias, the actual key aliased will be used.
     *
     * @param mixed $key
     * @param mixed $default Default value to use if key not found
     * @return mixed
     */
    public function getParam($key, $value = null)
    {
        if (isset($this -> _params[$key]))
        {
            return $this -> _params[$key];
        }
        elseif (isset($_GET[$key]))
        {
            return $_GET[$key];
        }
        elseif (isset($_POST[$key]))
        {
            return $_POST[$key];
        }

        return $value;
    }
    public function getPath()
    {
        if (null === $this -> _path)
        {
            $basePath= Agilet::getAppBasePath();
            
            $uri = $this -> getUri();
            
            // Remove the query string from REQUEST_URI
            if ($pos = strpos($uri, '?'))
            {
                $uri = substr($uri, 0, $pos);
            }

            if (!empty($basePath) && strpos($uri, $basePath) === 0)
            {
                $this->_path = substr($uri, strlen($basePath)); 
            }
            else
            {
                $this->_path = $uri;
            }
        }
        return $this -> _path;
    }
}
